// import util from '../../utils/util';
var app = getApp()
var tabbar = require('../../utils/tabbar');
import timeDateChoose from '../../utils/components/timeDatePicker/index'
import _config from '../../utils/config';
import _fetch from '../../utils/httpService';

Page({
  data: {
    showHeight: app.globalData.wHeight * 0.5,
    focusSearch: false,
    scrollTop: 0,
    queryParams: {
      pageSize: 20,
      pageNum: 1,
      startTime: null,
      endTime: null,
      isAbnormal: null,
      orderNo: null,
      orderStatus: [],
      templateIds: [],
      timeStatus: null
    },
    apointIndex: 0,
    isSearchClearShow: false,
    isSieve: false,
    orderStatusTemp: null,
    orderStatus: {
      itemType: '0',
      list: [],
    },
    orderStatusList: {
      listName: 'status',
      isExpend: true,
      itemType: '0',
      rowContent: '4',
      list: [{
        itemType: '1',
        name: '待受理',
        isActive: false,
      }, {
        itemType: '2',
        name: '待指派',
        isActive: false,
      }, {
        itemType: '3',
        name: '待接单',
        isActive: false,
      }, {
        itemType: '4',
        name: '待服务',
        isActive: false,
      }, {
        itemType: '5',
        name: '服务中',
        isActive: false,
      }, {
        itemType: '6',
        name: '已完成',
        isActive: false,
      }, {
        itemType: '7',
        name: '已取消',
        isActive: false,
      }],
      isMulti: true,
      typeList: []
    },
    startDate: {
      isStart: true,
      time: null,
      dateTimeArrayMin: null,
      dateTimeUnitArr: null,
      dateTimeMin: null,
      placeholder: '开始时间'
    },
    endDate: {
      isStart: false,
      time: null,
      dateTimeArrayMin: null,
      dateTimeUnitArr: null,
      dateTimeMin: null,
      placeholder: '结束时间'
    },
    dealTime: {
      dateTimeArrayMin: null,
      dateTimeUnitArr: null,
      dateTimeMin: null
    },
    timeList: {
      listName: 'time',
      isExpend: true,
      itemType: '',
      rowContent: '4',
      list: [{
        itemType: '0',
        name: '今天'
      }, {
        itemType: '1',
        name: '昨天'
      }, {
        itemType: '2',
        name: '近三天'
      }, {
        itemType: '3',
        name: '近七天'
      }]
    },
    orderTemplate: {
      listName: 'template',
      isExpend: false,
      itemType: '',
      rowContent: '4',
      list: [],
      isMulti: true,
      typeList: []
    },
    orderList: {
      hasButton: false,
      priorityList: ['一般', '紧急', '非常紧急'],
      statusList: [
        '',
        '待受理',
        '待指派',
        '待接单',
        '待服务',
        '服务中',
        '已完成',
        '已取消',
      ],
      isAbnormal: false,
      list: [],
      total: 0,
      isiOS: app.globalData.isiOS
    },
    apointList: [
      '预约时间',
      '创建时间',
      '完成时间'
    ],
    addList: [],
    isAdd: false,
    loading: true,
    isX: false,
    isiOS: false,
    isTotal: true,
    isChoose: false
  },
  onLoad: function (options) {
    // 生命周期函数--监听页面加载
    if (app.globalData.isService) {
      tabbar.tabbar("tabBar", 1, this)
    } else {
      tabbar.tabbar("tabBar", 0, this, 0)
    }
    this.setData({
      loading: true,
      isiOS: app.globalData.isiOS
    })
    wx.showLoading({
      title: '加载中',
    })
    if (app.globalData.formId) {
      if (app.globalData.formAbId) {
        wx.navigateTo({
          url: `../orderDetail/index?id=${app.globalData.formId}&fid=${app.globalData.formAbId}`
        })
      } else {
        wx.navigateTo({
          url: `../orderDetail/index?id=${app.globalData.formId}`
        })
      }
    }
  },
  onReady: function () {
    // 生命周期函数--监听页面初次渲染完成
  },
  onShow: function () {
    // 生命周期函数--监听页面显示
    let time = timeDateChoose.timeOnLoad(),
      timeMax = timeDateChoose.timeOnLoad('max')
    this.setData({
      'startDate.dateTimeMin': time.dateTimeMin,
      'startDate.dateTimeArrayMin': time.dateTimeArrayMin,
      'endDate.dateTimeArrayMin': time.dateTimeArrayMin,
      'startDate.dateTimeUnitArr': time.dateTimeUnitArrayMin,
      'endDate.dateTimeUnitArr': time.dateTimeUnitArrayMin,
      'endDate.dateTimeMin': time.dateTimeMin,
      'queryParams.pageNum': 1,
      'dealTime.dateTimeArrayMin': timeMax.dateTimeArrayMin,
      'dealTime.dateTimeUnitArr': time.dateTimeUnitArrayMin,
      'dealTime.dateTimeMin': timeMax.dateTimeMin,
      scrollTop: 0,
      isX: app.globalData.isX
    });
    this.getWorkNum()
    this.switchLoadList(false)
    this.getTemplateList()
  },
  onHide: function () {
    // 生命周期函数--监听页面隐藏
  },
  onUnload: function () {
    // 生命周期函数--监听页面卸载
    this.setData({
      'queryParams.pageNum': 1
    })
  },
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
  },
  onReachBottom: function () {
    // 页面上拉触底事件的处理函数
  },
  onShareAppMessage: function () {
    // 用户点击右上角分享
    return {
      title: '助力企业工单管理智能升级', // 分享标题
      desc: '', // 分享描述
      path: '/pages/login/index', // 分享路径
      imageUrl: '../../img/Mask.png' // 分享图片
    }
  },
  preventTouchMove() {
    return
  },
  getWorkNum() {
    // 获取状态列表
    let vm = this
    _fetch.get(_config.url.get_work_num)
      .then(function (data) {
        if (data && data.length > 0) {
          let arr = data.map(i => {
            return {
              itemType: i.orderStatus ? String(i.orderStatus) : '0',
              num: i.tableNum,
              name: i.tableName,
              isActive: i.orderStatus ? false : true,
              isShow: i.tableStatus === 0
            }
          })
          vm.setData({
            'orderStatus.list': arr
          })
        }
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  getTemplateList() {
    // 获取模版列表
    let vm = this
    _fetch.post(_config.url.get_template_list, {
      pageNum: 1,
      pageSize: 1000
    }).then(function (data) {
      if (data.rows && data.rows.length > 0) {
        let arr = data.rows.filter(i => {
          return i.status === 1
        })
        let final = arr.map(i => {
          return {
            isActive: false,
            itemType: i.templateId,
            name: i.templateName
          }
        })
        vm.setData({
          'orderTemplate.list': final,
          addList: arr
        })
      }
    }).catch(function (error) {
      wx.showToast({
        title: error.msg,
        icon: 'none',
      });
    });
  },
  loadList(isConcat) {
    // 加载列表
    let vm = this
    let params = this.data.queryParams.orderStatus.indexOf(10) > -1 ? {
      pageNum: this.data.queryParams.pageNum,
      pageSize: this.data.queryParams.pageSize,
      // orderStatus: 10,
      startTime: this.data.queryParams.startTime,
      endTime: this.data.queryParams.endTime,
      templateIds: this.data.queryParams.templateIds,
      timeStatus: this.data.queryParams.timeStatus,
      orderNo: this.data.queryParams.orderNo
    } : this.data.queryParams
    let url = this.data.queryParams.orderStatus.indexOf(10) > -1 ? _config.url.search_err_work : _config.url.search_work
    _fetch.post(url, params)
      .then(function (data) {
        let orderList = data.rows ? data.rows : []
        setTimeout(() => {
          vm.setData({
            'orderList.list': isConcat ? vm.data.orderList.list.concat(orderList) : orderList,
            'orderList.total': data.total,
            'orderList.isAbnormal': vm.data.queryParams.orderStatus.indexOf(10) > -1
          })
        }, 0);
        vm.setData({
          loading: false
        })
        wx.hideLoading()
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  scrollLoadTop() {
    this.setData({
      'queryParams.pageNum': 1
    })
    this.getWorkNum()
    this.switchLoadList(false)
  },
  scrollLoadList() {
    // 滚动工单列表事件
    this.setData({
      'queryParams.pageNum': this.data.queryParams.pageNum + 1
    })
    if (this.data.orderList.list.length !== this.data.orderList.total) {
      this.switchLoadList(true)
    }
  },
  focusSearchInput() {
    this.setData({
      focusSearch: true
    })
  },
  showClear(e) {
    // 搜索框输入
    if (e.detail.value) {
      this.setData({
        'queryParams.orderNo': e.detail.value,
        isSearchClearShow: true,
        focusSearch: true
      })
    } else {
      this.setData({
        'queryParams.orderNo': e.detail.value,
        isSearchClearShow: false,
        focusSearch: true
      })
    }
  },
  toSearch(event) {
    // 搜索
    if (event.detail.value) {
      this.setData({
        'queryParams.orderNo': event.detail.value,
        'queryParams.pageNum': 1
      })
      this.switchLoadList(false)
    } else {
      this.setData({
        'queryParams.orderNo': event.detail.value
      })
    }
  },
  tapSearchClear() {
    // 清空搜索
    this.setData({
      isSearchClearShow: false,
      'queryParams.orderNo': '',
      'queryParams.pageNum': 1,
      scrollTop: 0,
      focusSearch: this.data.focusSearch
    })
    this.switchLoadList(false)
  },
  cancelSieve() {
    // 重置筛选
    let time = timeDateChoose.timeOnLoad()
    let status = (this.data.orderStatusTemp && this.data.orderStatusTemp != '0') ? [Number(this.data.orderStatusTemp)] : []
    this.data.orderStatusList.list.map(i => {
      i.isActive = i.itemType === '0' ? true : false
    })
    this.data.orderTemplate.list.map(i => {
      i.isActive = false
    })
    this.setData({
      queryParams: {
        pageSize: 20,
        pageNum: 1,
        startTime: null,
        endTime: null,
        isAbnormal: null,
        orderNo: null,
        orderStatus: status,
        templateIds: [],
        timeStatus: 1
      },
      'startDate.dateTimeMin': time.dateTimeMin,
      'startDate.dateTimeArrayMin': time.dateTimeArrayMin,
      'endDate.dateTimeArrayMin': time.dateTimeArrayMin,
      'startDate.dateTimeUnitArr': time.dateTimeUnitArrayMin,
      'endDate.dateTimeUnitArr': time.dateTimeUnitArrayMin,
      'endDate.dateTimeMin': time.dateTimeMin,
      'orderStatusList.itemType': '',
      'orderStatusList.list': this.data.orderStatusList.list,
      'orderStatusList.typeList': [],
      'timeList.itemType': '',
      'startDate.time': null,
      'endDate.time': null,
      'orderTemplate.itemType': '',
      'orderTemplate.list': this.data.orderTemplate.list,
      'orderTemplate.typeList': [],
      apointIndex: 0
    })
  },
  confirmSieve() {
    // 确定筛选
    this.setData({
      'queryParams.pageNum': 1
    })
    console.log(this.data.isTotal)
    if (this.data.isTotal) {
      this.loadList(false)
    } else {
      this.switchLoadList(false)
    }
    this.computedIsChoose()
    this.setData({
      isSieve: false
    })
  },
  computedIsChoose() {
    if (this.data.queryParams.startTime != null || this.data.queryParams.endTime != null) {
      this.setData({
        isChoose: true
      })
    } else if ((this.data.orderStatus.itemType == '0' && this.data.orderStatusList.typeList.length > 0) || this.data.queryParams.templateIds.length > 0) {
      this.setData({
        isChoose: true
      })
    } else {
      this.setData({
        isChoose: false
      })
    }
  },
  otherStatusLoad(url, params, isConcat) {
    let vm = this
    _fetch.post(url, params)
      .then(function (data) {
        let orderList = data.rows ? data.rows : []
        setTimeout(() => {
          vm.setData({
            'orderList.list': isConcat ? vm.data.orderList.list.concat(orderList) : orderList,
            'orderList.total': data.total,
            'orderList.isAbnormal': false
          })
        }, 0);
        vm.setData({
          loading: false
        })
        wx.hideLoading()
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  switchLoadList(isConcat) {
    let temp = JSON.stringify(this.data.queryParams),
        queryTemp = JSON.parse(temp)
    let status = Array.isArray(queryTemp.orderStatus) ? queryTemp.orderStatus[0] : queryTemp.orderStatus,
      params = queryTemp,
      vm = this
    switch (status) {
      case 1: // 待我受理
        params.acceptStatus = 1
        vm.otherStatusLoad(_config.url.search_accept_work, params, isConcat)
        break;
      case 2: // 待我指派
        vm.otherStatusLoad(_config.url.search_assign_work, params, isConcat)
        break;
      case 4: // 待我服务
        params.orderStatus = 4
        vm.otherStatusLoad(_config.url.search_service_work, params, isConcat)
        break;
      case 5: // 待我完成
        params.orderStatus = 5
        vm.otherStatusLoad(_config.url.search_service_work, params, isConcat)
        break;
      default:
        this.loadList(isConcat)
        break;
    }
  },
  chooseStauts(event) {
    // 选择状态
    let status = event.currentTarget.dataset.itemtype
    if (status) {
      this.setData({
        'orderStatus.itemType': status,
        orderStatusTemp: status,
        'queryParams.pageNum': 1,
        'queryParams.orderStatus': status !== '0' ? [Number(status)] : this.data.orderStatusList.typeList,
        scrollTop: 0,
        isTotal: status !== '0' ? false : true
        // isSieve: false
      })
      this.switchLoadList(false)
      this.computedIsChoose()
    } else {
      this.setData({
        'orderStatusList.itemType': ''
      })
    }
  },
  openSieve() {
    // 点击筛选
    if (!this.data.isSieve) {
      this.setData({
        // orderStatusTemp: this.data.orderStatusList.itemType
        'queryParams.timeStatus': 1
      })
    } else {
      this.setData({
        // 'orderStatusList.itemType': this.data.orderStatusTemp
        'queryParams.timeStatus': null
      })
      this.computedIsChoose()
      // this.cancelSieve()
    }
    this.setData({
      isSieve: !this.data.isSieve
    })
  },
  toExpend() {
    // 展开模版
    this.setData({
      'orderTemplate.isExpend': !this.data.orderTemplate.isExpend
    })
  },
  cutDate(date, range) {
    // 减少时间
    let day = range === 1 ? date[2] - 1 : range === 3 ? date[2] - 3 : date[2] - 7,
      month = date[1],
      year = date[0];
    if (day < 0) {
      month = month - 1
      if (month === 0 || month === 2 || month === 4 || month === 6 || month === 7 || month === 9 || month === 11) {
        day = 31 + day
      } else if (month === 1) {
        day = 29 + day
      } else {
        day = 30 + day
      }
    }
    if (month < 0) {
      year = year - 1
      month = 12 + month
    }
    return [year, month, day]
  },
  dealTime(type) {
    // 计算时间范围
    let time = timeDateChoose.timeOnLoad('max'),
      start, end
    if (type === '0') {
      start = time.dateTimeMin.slice(0, 3).concat([0, 0])
      end = time.dateTimeMin.slice(0, 3).concat([23, 59])
    } else if (type === '1') {
      start = this.cutDate(time.dateTimeMin.slice(0, 3), 1).concat([0, 0])
      end = this.cutDate(time.dateTimeMin.slice(0, 3), 1).concat([23, 59])
    } else if (type === '2') {
      start = this.cutDate(time.dateTimeMin.slice(0, 3), 3).concat(time.dateTimeMin.slice(3, 6))
      end = time.dateTimeMin.slice(0, 3).concat(time.dateTimeMin.slice(3, 6))
    } else {
      start = this.cutDate(time.dateTimeMin.slice(0, 3), 7).concat(time.dateTimeMin.slice(3, 6))
      end = time.dateTimeMin.slice(0, 3).concat(time.dateTimeMin.slice(3, 6))
    }
    return {
      start: start,
      end: end
    }
  },
  chooseButton(e) {
    // tagButton点击事件
    console.log(e)
    let index = e.currentTarget.dataset.iindex
    let name = e.currentTarget.dataset.listname
    let type = e.currentTarget.dataset.itemtype
    if (name) {
      if (name == 'status') {
        // 状态tag
        if (type) {
          this.data.orderStatusList.list[index].isActive = !this.data.orderStatusList.list[index].isActive
          if (this.data.orderStatusList.typeList.indexOf(Number(type)) > -1) {
            let idx = this.data.orderStatusList.typeList.indexOf(Number(type))
            this.data.orderStatusList.typeList.splice(idx, 1)
            this.data.queryParams.orderStatus.splice(idx, 1)
          } else {
            this.data.orderStatusList.typeList.push(Number(type))
            this.data.queryParams.orderStatus.push(Number(type))
          }
          this.setData({
            'queryParams.orderStatus': this.data.queryParams.orderStatus,
            'orderStatusList.typeList': this.data.orderStatusList.typeList,
            'orderStatusList.itemType': this.data.isSieve ? this.data.orderStatusList.itemType : type,
            'orderStatusList.list': this.data.orderStatusList.list
          })
        } else {
          this.data.orderStatusList.typeList = [0]
          this.data.orderStatusList.list[0].isActive = true
          this.setData({
            'queryParams.orderStatus': [],
            'orderStatusList.typeList': this.data.orderStatusList.typeList,
            'orderStatusList.itemType': '0',
            'orderStatusList.list': this.data.orderStatusList.list
          })
        }
      } else if (name == 'time') {
        // 时间tag
        if (type) {
          let time = this.dealTime(type)
          let start = this.returnDate(time.start)
          let end = this.returnDate(time.end)
          console.log(start, end)
          let arrS = timeDateChoose.timeOnLoad('default', start[1])
          let arrE = timeDateChoose.timeOnLoad('default', end[1])

          this.setData({
            'timeList.itemType': type,
            'startDate.dateTimeMin': time.start,
            'endDate.dateTimeMin': time.end,
            'startDate.dateTimeArrayMin': arrS.dateTimeArrayMin,
            'endDate.dateTimeArrayMin': arrE.dateTimeArrayMin,
            'startDate.dateTimeUnitArr': arrS.dateTimeUnitArrayMin,
            'endDate.dateTimeUnitArr': arrE.dateTimeUnitArrayMin,
            'startDate.time': start[0],
            'endDate.time': end[0],
            'queryParams.startTime': start[0],
            'queryParams.endTime': end[0]
          })
        } else {
          this.setData({
            'timeList.itemType': ''
          })
        }
      } else {
        // 模版tag
        if (type) {
          console.log(type)
          this.data.orderTemplate.list[index].isActive = !this.data.orderTemplate.list[index].isActive
          if (this.data.orderTemplate.typeList.indexOf(type) > -1) {
            let idx = this.data.orderTemplate.typeList.indexOf(type)
            console.log(idx)
            this.data.orderTemplate.typeList.splice(idx, 1)
            this.data.queryParams.templateIds.splice(idx, 1)
          } else {
            this.data.queryParams.templateIds.push(type)
            this.data.orderTemplate.typeList.push(type)
          }
          console.log(this.data.orderTemplate.typeList)
          console.log(this.data.queryParams.templateIds)
          this.setData({
            'queryParams.templateIds': this.data.queryParams.templateIds,
            'orderTemplate.itemType': this.data.isSieve ? this.data.orderTemplate.itemType : type,
            'orderTemplate.list': this.data.orderTemplate.list
          })
        } else {
          this.data.orderTemplate.list = []
          this.setData({
            'queryParams.templateIds': [],
            'orderTemplate.itemType': '',
            'orderTemplate.list': []
          })
        }
      }
    }
  },
  returnDate(arr) {
    // 处理时间
    let dateTimeTemp = this.data.dealTime.dateTimeArrayMin[0][arr[0]] + '-' + this.data.dealTime.dateTimeArrayMin[1][arr[1]] + '-' + this.data.dealTime.dateTimeArrayMin[2][arr[2]] + ' ' + this.data.dealTime.dateTimeArrayMin[3][arr[3]] + ':' + this.data.dealTime.dateTimeArrayMin[4][arr[4]]
    let dateTime = this.data.isiOS ? (dateTimeTemp.replace('-', '/').replace('-', '/')) : dateTimeTemp
    let date = Number(new Date(dateTime))
    return [date, dateTimeTemp]
  },
  changeDateTimeMin(e) {
    // 选择时间
    let time = timeDateChoose.changeDateTimeMin(e)
    if (e.currentTarget.dataset.isstart) {
      let date = this.returnDate(time)
      console.log(date)
      if (this.data.endDate.time) {
        if (this.data.endDate.time > date[0]) {
          this.setData({
            'startDate.dateTimeMin': time,
            'startDate.time': date[0],
            'queryParams.startTime': date[0]
          })
        } else {
          wx.showToast({
            title: '开始时间不能小于结束时间',
            icon: 'none',
          });
        }
      } else {
        this.setData({
          'startDate.dateTimeMin': time,
          'startDate.time': date[0],
          'queryParams.startTime': date[0]
        })
      }
    } else {
      let date = this.returnDate(time)
      if (this.data.startDate.time) {
        if (this.data.startDate.time < date[0]) {
          this.setData({
            'endDate.dateTimeMin': time,
            'queryParams.endTime': date[0],
            'endDate.time': date[0]
          })
        } else {
          wx.showToast({
            title: '开始时间不能小于结束时间',
            icon: 'none',
          });
        }
      } else {
        this.setData({
          'queryParams.endTime': date[0],
          'endDate.dateTimeMin': time,
          'endDate.time': date[0]
        })
      }
    }
  },
  showDetail(e) {
    // 跳转至工单详情
    if (e.currentTarget.dataset.formid) {
      if (e.currentTarget.dataset.formAbId) {
        wx.navigateTo({
          url: `../orderDetail/index?id=${e.currentTarget.dataset.formid}&fid=${e.currentTarget.dataset.formAbId}`
        })
      } else {
        wx.navigateTo({
          url: `../orderDetail/index?id=${e.currentTarget.dataset.formid}`
        })
      }
    }
  },
  toAdd() {
    // 打开新增
    if (!this.data.isAdd) {
      wx.hideTabBar()
    } else {
      wx.showTabBar()
    }
    this.setData({
      'isAdd': !this.data.isAdd
    })
  },
  addOrder(e) {
    // 跳转至新增工单
    if (e.currentTarget.dataset.templateid) {
      wx.navigateTo({
        url: `../orderAdd/index?id=${e.currentTarget.dataset.templateid}&name=${e.currentTarget.dataset.templatename}`
      })
    }
  },
  bindPickerApointTime(e) {
    // 选择时间状态
    if (e.detail.value) {
      this.setData({
        apointIndex: Number(e.detail.value),
        'queryParams.timeStatus': Number(e.detail.value) + 1
      })
    }
  }
})